var app = getApp()
import {
  getCart,
  checkedAll,
  checkedCart,
  delCart,
  editCartNum,
  clearCart,
} from '../../api/cart'
import {
  getGoods
} from '../../api/goods'
Page({
  data: {
    goodsList: {
      saveHidden: true,
      totalPrice: 0,
      allSelect: true,
      noSelect: false,
      list: [],
      totalNumber: 0,
    },
    delBtnWidth: 120, //删除按钮宽度单位（rpx）
  },

  //获取元素自适应后的实际宽度
  getEleWidth: function (w) {
    var real = 0;
    try {
      var res = wx.getSystemInfoSync().windowWidth;
      var scale = (750 / 2) / (w / 2); //以宽度750px设计稿做宽度的自适应
      // console.log(scale);
      real = Math.floor(res / scale);
      return real;
    } catch (e) {
      return false;
      // Do something when catch error
    }
  },
  initEleWidth: function () {
    var delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
    this.setData({
      delBtnWidth: delBtnWidth
    });
  },
  toDetailsTap: function (e) {
    wx.navigateTo({
      url: "/pages/goods-detail/goods-detail?id=" + e.currentTarget.dataset.id
    })
  },
  async getData() {
    let res = await getGoods(1, 100, '', '', wx.getStorageSync('access_token') ? wx.getStorageSync('access_token') : '')
    if( res.data.records.length > 0 ){
      this.setData({
        sales: res.data.records,
      })
    }
  },
  goDetail(e) {
    let IsBuy = e.currentTarget.dataset.dealer;
    let Id = e.currentTarget.dataset.id;
    let url = `/pages/goods-detail/goods-detail?isDealer=${IsBuy}&id=${Id}`
    wx.navigateTo({
      url,
    })
  },
  onLoad: function () {
    var that = this;
    if (app.globalData.iphone == true) {
      that.setData({
        iphone: 'iphone'
      })
    }
    wx.hideShareMenu()
    // wx.request({
    //   url: app.globalData.urls + '/config/get-value',
    //   data: {
    //     key: 'shopcart'
    //   },
    //   success: function (res) {
    //     if (res.data.code == 0) {
    //       var kb = res.data.data.value;
    //       var kbarr = kb.split(',');
    //       that.setData({
    //         sales: res.data.data
    //       });
    //       var sales = [];
    //       for (var i = 0; i < kbarr.length; i++) {
    //         wx.request({
    //           url: app.globalData.urls + '/shop/goods/detail',
    //           data: {
    //             id: kbarr[i]
    //           },
    //           success: function (res) {
    //             if (res.data.code == 0) {
    //               sales.push(res.data.data.basicInfo);
    //             }
    //             that.setData({
    //               sales: sales
    //             });
    //           }
    //         })
    //       }
    //     }
    //   }
    // })

    that.initEleWidth();
  },
  async onShow() {
    var that = this
    let res = await getCart(wx.getStorageSync('access_token'))
    this.getData()
    if (res && res.code == 10000) {
      let list = res.data.cartList[0].skuList.map(item => {
        return {
          active: item.checked,
          checkNum: false,
          pic: item.goodsSku.original,
          name: item.goodsSku.goodsName,
          id: item.goodsSku.id,
          number: item.num,
          label: item.goodsSku.simpleSpecs,
          price: item.purchasePrice,
          standardId: item.goodsSku.id,
          invalid: item.invalid,
          errorMsg: item.errorMessage
        }
      })
      this.setData({
        goodsList:{
          list
        }
      })
      that.setGoodsList(that.getSaveHide(), that.totalPrice(), that.allSelect(), that.noSelect(), list)
    }
  },
  toIndexPage: function () {
    wx.switchTab({
      url: "/pages/index/index"
    });
  },

  touchS: function (e) {
    if (e.touches.length == 1) {
      this.setData({
        startX: e.touches[0].clientX
      });
    }
  },
  touchM: function (e) {
    var index = e.currentTarget.dataset.index;

    if (e.touches.length == 1) {
      var moveX = e.touches[0].clientX;
      var disX = this.data.startX - moveX;
      var delBtnWidth = this.data.delBtnWidth;
      var left = "";
      if (disX == 0 || disX < 0) { //如果移动距离小于等于0，container位置不变
        left = "margin-left:0px";
      } else if (disX > 0) { //移动距离大于0，container left值等于手指移动距离
        left = "margin-left:-" + disX + "px";
        if (disX >= delBtnWidth) {
          left = "left:-" + delBtnWidth + "px";
        }
      }
      var list = this.data.goodsList.list;
      if (index != "" && index != null) {
        list[parseInt(index)].left = left;
        this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
      }
    }
  },

  touchE: function (e) {
    var index = e.currentTarget.dataset.index;
    if (e.changedTouches.length == 1) {
      var endX = e.changedTouches[0].clientX;
      var disX = this.data.startX - endX;
      var delBtnWidth = this.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      var left = disX > delBtnWidth / 2 ? "margin-left:-" + delBtnWidth + "px" : "margin-left:0px";
      var list = this.data.goodsList.list;
      if (index !== "" && index != null) {
        list[parseInt(index)].left = left;
        this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);

      }
    }
  },
  async delItem(e) {
    var index = e.currentTarget.dataset.index;
    var list = this.data.goodsList.list;
    let _this = this;
    // console.log(e);
    wx.showLoading({
      title: '处理中...',
    })
    let skuIds = []
    skuIds.push(list[index].id)
    let res = await delCart(skuIds, wx.getStorageSync('access_token'))
    console.log(res)
    if (res.code == 10000) {
      wx.hideLoading()
      wx.showToast({
        title: '删除成功',
      })
      list.splice(index, 1)
      _this.setGoodsList(_this.getSaveHide(), _this.totalPrice(), _this.allSelect(), _this.noSelect(), list);
    }
    // app.postForm("/cart/delete_cart", {
    //   CustId: app.globalData.uid,
    //   GoodsId: list[index].id,
    //   StandardId: list[index].standardId
    // }, function (res) {
    //   wx.hideLoading();
    //   if (res && res.code == "0") {
    //     list.splice(index, 1);
    //     _this.setGoodsList(_this.getSaveHide(), _this.totalPrice(), _this.allSelect(), _this.noSelect(), list);
    //   }
    // })
  },
  async selectTap(e) {
    var index = e.currentTarget.dataset.index
    var list = this.data.goodsList.list
    if( list[parseInt(index)].invalid ){
      return
    }
    console.log(list[parseInt(index)].id)
    if (index !== "" && index != null) {
      await checkedCart(list[parseInt(index)].id, !list[parseInt(index)].active, wx.getStorageSync('access_token'))
      list[parseInt(index)].active = !list[parseInt(index)].active;
      this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
    }
  },
  totalPrice: function () {
    var list = this.data.goodsList.list
    var total = 0;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      if (curItem.active) {
        total += parseFloat(curItem.price) * curItem.number;
      }
    }
    total = parseFloat(total.toFixed(2)); //js浮点计算bug，取两位小数精度
    return total
  },
  allSelect: function () {
    var list = this.data.goodsList.list;
    var allSelect = false;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      if (curItem.active) {
        allSelect = true;
      } else {
        allSelect = false;
        break;
      }
    }
    return allSelect;
  },
  noSelect: function () {
    var list = this.data.goodsList.list
    var noSelect = 0;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      if (!curItem.active) {
        noSelect++;
      }
    }
    if (noSelect == list.length) {
      return true;
    } else {
      return false;
    }
  },
  setGoodsList: function (saveHidden, total, allSelect, noSelect, list) {
    this.setData({
      goodsList: {
        saveHidden: saveHidden,
        totalPrice: total,
        allSelect: allSelect,
        noSelect: noSelect,
        list: list
      }
    })
    // var shopCarInfo = {};
    var tempNumber = 0;
    // shopCarInfo.shopList = list
    for (var i = 0; i < list.length; i++) {
      tempNumber = tempNumber + list[i].number
    }
    // shopCarInfo.shopNum = tempNumber
    // wx.setStorage({
    //   key: "shopCarInfo",
    //   data: shopCarInfo
    // })
  },
  async bindAllSelect() {
    var currentAllSelect = this.data.goodsList.allSelect;
    var list = this.data.goodsList.list;
    if (currentAllSelect) {
      for (var i = 0; i < list.length; i++) {
        var curItem = list[i];
        curItem.active = false
      }
      await checkedAll(false, wx.getStorageSync('access_token'))
    } else {
      for (var i = 0; i < list.length; i++) {
        var curItem = list[i]
        curItem.active = true
        if(curItem.invalid){
          curItem.active = false
        }
      }
      await checkedAll(true, wx.getStorageSync('access_token'))
    }

    this.setGoodsList(this.getSaveHide(), this.totalPrice(), !currentAllSelect, this.noSelect(), list);
  },
  checkNumTap: function (e) {
    var index = e.currentTarget.dataset.index;
    var list = this.data.goodsList.list;
    if (index !== "" && index != null) {
      if (!list[parseInt(index)].active) {
        return;
      } else {
        list[parseInt(index)].checkNum = true
        this.setData({
          goodsList: this.data.goodsList
        })
      }
    }
  },
  onPageScroll() {
    this.data.goodsList.list.forEach(item => {
      item.checkNum = false
    })
    this.setData({
      goodsList: this.data.goodsList
    })
  },
  async jiaBtnTap(e) {
    var index = e.currentTarget.dataset.index;
    var list = this.data.goodsList.list;
    if (index !== "" && index != null) {
      if (!list[parseInt(index)].active) {
        return;
      }
      list[parseInt(index)].number++
        let _this = this
        wx.showLoading({
          title: '处理中',
          mask: true
        })
        let res = await editCartNum(list[parseInt(index)].id, Number(list[parseInt(index)].number), wx.getStorageSync('access_token'))
        console.log(res)
        if (res && res.code == 10000) {
          wx.hideLoading()
          _this.setGoodsList(_this.getSaveHide(), _this.totalPrice(), _this.allSelect(), _this.noSelect(), list)
        }
    }
  },
  async jianBtnTap(e) {
    var index = e.currentTarget.dataset.index;
    var list = this.data.goodsList.list;
    if (index !== "" && index != null) {
      if (!list[parseInt(index)].active) {
        return;
      }
      if (list[parseInt(index)].number > 1) {
        list[parseInt(index)].number--;
        let _this = this;
        wx.showLoading({
          title: '处理中',
          mask: true
        })
        let res = await editCartNum(list[parseInt(index)].id, Number(list[parseInt(index)].number), wx.getStorageSync('access_token'))
        console.log(res)
        if (res && res.code == 10000) {
          wx.hideLoading()
          _this.setGoodsList(_this.getSaveHide(), _this.totalPrice(), _this.allSelect(), _this.noSelect(), list)
        }
      }
    }
  },
  editTap: function () {
    var list = this.data.goodsList.list;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      curItem.active = false;
    }
    this.setGoodsList(!this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
  },
  saveTap: function () {
    var list = this.data.goodsList.list;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      curItem.active = true;
    }
    this.setGoodsList(!this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
  },
  getSaveHide: function () {
    var saveHidden = this.data.goodsList.saveHidden;
    return saveHidden;
  },
  deleteSelected: function () {
    var list = this.data.goodsList.list;
    /*
     for(let i = 0 ; i < list.length ; i++){
           let curItem = list[i];
           if(curItem.active){
             list.splice(i,1);
           }
     }
     */
    // above codes that remove elements in a for statement may change the length of list dynamically
    list = list.filter(function (curGoods) {
      return !curGoods.active;
    });
    this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
    //更新tabbar购物车数字角标
  },
  toPayOrder: function () {
    wx.showLoading();
    var that = this;
    if (this.data.goodsList.noSelect) {
      wx.hideLoading();
      return;
    }
    this.navigateToPayOrder();
    // for (let i = 0; i < shopList.length; i++) {
    //   if (isFail) {
    //     wx.hideLoading();
    //     return;
    //   }
    // let carShopBean = shopList[i];
    // // 获取价格和库存
    // if (!carShopBean.propertyChildIds || carShopBean.propertyChildIds == "") {
    //   wx.request({
    //     url: app.globalData.urls + '/shop/goods/detail',
    //     data: {
    //       id: carShopBean.goodsId
    //     },
    //     success: function (res) {
    //       doneNumber++;
    //       if (res.data.data.properties) {
    //         wx.showModal({
    //           title: '提示',
    //           content: res.data.data.basicInfo.name + ' 商品已失效，请重新购买',
    //           showCancel: false
    //         })
    //         isFail = true;
    //         wx.hideLoading();
    //         return;
    //       }
    //       if (res.data.data.basicInfo.stores < carShopBean.number) {
    //         wx.showModal({
    //           title: '提示',
    //           content: res.data.data.basicInfo.name + ' 库存不足，请重新购买',
    //           showCancel: false
    //         })
    //         isFail = true;
    //         wx.hideLoading();
    //         return;
    //       }
    //       if (res.data.data.basicInfo.minPrice != carShopBean.price) {
    //         wx.showModal({
    //           title: '提示',
    //           content: res.data.data.basicInfo.name + ' 价格有调整，请重新购买',
    //           showCancel: false
    //         })
    //         isFail = true;
    //         wx.hideLoading();
    //         return;
    //       }
    //       if (needDoneNUmber == doneNumber) {
    //         that.navigateToPayOrder();
    //       }
    //     }
    //   })
    // } else {
    //   wx.request({
    //     url: app.globalData.urls + '/shop/goods/price',
    //     data: {
    //       goodsId: carShopBean.goodsId,
    //       propertyChildIds: carShopBean.propertyChildIds
    //     },
    //     success: function (res) {
    //       doneNumber++;
    //       if (res.data.data.stores < carShopBean.number) {
    //         wx.showModal({
    //           title: '提示',
    //           content: carShopBean.name + ' 库存不足，请重新购买',
    //           showCancel: false
    //         })
    //         isFail = true;
    //         wx.hideLoading();
    //         return;
    //       }
    //       if (res.data.data.price != carShopBean.price) {
    //         wx.showModal({
    //           title: '提示',
    //           content: carShopBean.name + ' 价格有调整，请重新购买',
    //           showCancel: false
    //         })
    //         isFail = true;
    //         wx.hideLoading();
    //         return;
    //       }
    //       if (needDoneNUmber == doneNumber) {
    //         that.navigateToPayOrder();
    //       }
    //     }
    //   })
    // }

    // }
  },
  navigateToPayOrder: function () {
    wx.hideLoading();
    wx.redirectTo({
      url: "/pages/pay-order/pay-order?orderType=CART"
    })
  }
})